package com.michale.framework.filters;

import com.alibaba.fastjson2.JSON;
import com.michale.common.annotation.NotRepeatSubmit;
import com.michale.common.result.AjaxResult;
import com.michale.common.utils.Ip.ServletUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Michale
 * @apiNote 防止重复提交拦截器
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            NotRepeatSubmit notRepeatSubmit = method.getAnnotation(NotRepeatSubmit.class);
            if (notRepeatSubmit != null) {
                if (this.isRepeatSubmit(request, notRepeatSubmit)) {
                    AjaxResult ajaxResult = AjaxResult.error(notRepeatSubmit.message());
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交
     * 由子类实现具体地防止重复提交的规则
     *
     * @param request 请求域
     * @return true/false
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, NotRepeatSubmit notRepeatSubmit);

}
